'use client';

import { useState, useCallback, useEffect } from 'react';
import { useApi } from '@/hooks/use-api';
import { useSocket } from '@/hooks/use-socket';
import { useAuth } from '@/hooks/use-auth';
import { notifications } from '@/components/ui/notification-toast';
import { TASK_STATUS } from '@/lib/constants';
import { handleApiError } from '@/lib/error-handler';
import { taskStatusToApiFormat, taskStatusFromApiFormat } from '@/lib/utils';

// 任务类型定义
export interface Task {
  id: string;
  title: string;
  description?: string;
  status: string;
  priority: string;
  assigneeId?: string;
  assignee?: {
    id: string;
    name: string;
    image?: string;
  };
  createdBy: {
    id: string;
    name: string;
    image?: string;
  };
  projectId: string;
  dueDate?: string;
  createdAt: string;
  updatedAt: string;
  tags?: string[];
  attachments?: number;
  comments?: number;
  isOverdue?: boolean;
}

// 任务更新数据类型
export interface TaskUpdateData {
  title?: string;
  description?: string;
  status?: string;
  priority?: string;
  assigneeId?: string;
  dueDate?: string;
  tags?: string[];
}

// 任务Hook选项
interface UseTaskOptions {
  projectId?: string;
  taskId?: string;
  autoFetch?: boolean;
  enableRealtime?: boolean;
  showNotifications?: boolean;
}

/**
 * 任务管理Hook
 * 
 * 整合任务相关的API调用、实时更新和状态管理
 * 
 * @example
 * ```tsx
 * const { 
 *   tasks, 
 *   isLoading, 
 *   updateTask, 
 *   deleteTask 
 * } = useTask({ projectId: "123" });
 * ```
 */
export function useTask({
  projectId,
  taskId,
  autoFetch = true,
  enableRealtime = true,
  showNotifications = true
}: UseTaskOptions = {}) {
  // 获取用户信息
  const { user } = useAuth();
  
  // 获取Socket连接
  const { 
    isConnected: isSocketConnected, 
    joinProject, 
    joinTask,
    leaveProject,
    leaveTask,
    sendTaskUpdate,
    onTaskUpdated
  } = useSocket();
  
  // 任务列表API
  const {
    data: tasks,
    setData: setTasks,
    isLoading: isTasksLoading,
    error: tasksError,
    refetch: refetchTasks,
    post: createTaskApi,
    put: updateTaskApi,
    delete: deleteTaskApi
  } = useApi<Task[]>(
    projectId ? `/api/projects/${projectId}/tasks` : '/api/tasks',
    {
      autoFetch: autoFetch && !!projectId && !taskId,
      useCache: true,
      cacheKey: projectId ? `tasks_${projectId}` : 'tasks',
      showErrorNotification: showNotifications,
      errorNotificationTitle: '获取任务失败',
      deps: [projectId]
    }
  );
  
  // 单个任务API
  const {
    data: task,
    setData: setTask,
    isLoading: isTaskLoading,
    error: taskError,
    refetch: refetchTask,
    put: updateSingleTaskApi,
    delete: deleteSingleTaskApi
  } = useApi<Task>(
    taskId ? `/api/tasks/${taskId}` : '',
    {
      autoFetch: autoFetch && !!taskId,
      useCache: true,
      cacheKey: taskId ? `task_${taskId}` : '',
      showErrorNotification: showNotifications,
      errorNotificationTitle: '获取任务详情失败',
      deps: [taskId]
    }
  );
  
  // 加入项目和任务的Socket房间
  useEffect(() => {
    if (!isSocketConnected || !enableRealtime) return;
    
    if (projectId) {
      joinProject(projectId);
    }
    
    if (taskId) {
      joinTask(taskId);
    }
    
    return () => {
      if (projectId) {
        leaveProject(projectId);
      }
      
      if (taskId) {
        leaveTask(taskId);
      }
    };
  }, [projectId, taskId, isSocketConnected, enableRealtime, joinProject, joinTask, leaveProject, leaveTask]);
  
  // 监听任务更新事件
  useEffect(() => {
    if (!isSocketConnected || !enableRealtime) return;
    
    const handleTaskUpdated = (data: any) => {
      try {
        // 更新单个任务
        if (taskId && taskId === data.taskId) {
          setTask((prevTask) => {
            if (!prevTask) return prevTask;
            
            return {
              ...prevTask,
              ...data.update,
              updatedAt: new Date().toISOString()
            };
          });
          
          if (showNotifications) {
            notifications.info(
              '任务已更新',
              `${data.updatedBy?.name || '有人'} 更新了任务`
            );
          }
        }
        
        // 更新任务列表
        if (tasks && projectId && projectId === data.projectId) {
          setTasks((prevTasks) => {
            if (!prevTasks) return prevTasks;
            
            return prevTasks.map((t) => {
              if (t.id === data.taskId) {
                return {
                  ...t,
                  ...data.update,
                  updatedAt: new Date().toISOString()
                };
              }
              return t;
            });
          });
        }
      } catch (error) {
        console.error('处理任务更新事件失败:', error);
      }
    };
    
    // 注册事件监听器
    const unsubscribe = onTaskUpdated(handleTaskUpdated);
    
    return unsubscribe;
  }, [isSocketConnected, enableRealtime, taskId, projectId, tasks, setTask, setTasks, onTaskUpdated, showNotifications]);
  
  // 创建任务
  const createTask = useCallback(async (taskData: Omit<TaskUpdateData, 'id'>) => {
    if (!projectId) {
      throw new Error('缺少项目ID');
    }
    
    try {
      // 添加默认值
      const newTaskData = {
        ...taskData,
        status: taskData.status || TASK_STATUS.TODO,
        createdBy: {
          id: user?.id || '',
          name: user?.name || '未知用户'
        }
      };
      
      // 调用API创建任务
      const createdTask = await createTaskApi(newTaskData);
      
      // 更新本地任务列表
      if (createdTask && tasks) {
        setTasks([...tasks, createdTask]);
      }
      
      if (showNotifications) {
        notifications.success('创建成功', '任务已创建');
      }
      
      return createdTask;
    } catch (error) {
      handleApiError(error);
      throw error;
    }
  }, [projectId, user, createTaskApi, tasks, setTasks, showNotifications]);
  
  // 更新任务
  const updateTask = useCallback(async (taskIdOrTask: string | Task, updateData: TaskUpdateData) => {
    try {
      // 确定任务ID
      const taskId = typeof taskIdOrTask === 'string' ? taskIdOrTask : taskIdOrTask.id;
      
      // 如果包含状态，确保使用API格式
      if (updateData.status) {
        updateData.status = taskStatusToApiFormat(updateData.status);
      }
      
      // 调用API更新任务
      const updatedTask = await updateTaskApi(taskId, updateData);
      
      // 更新本地任务列表
      if (updatedTask && tasks) {
        setTasks(tasks.map(t => t.id === taskId ? updatedTask : t));
      }
      
      // 更新单个任务
      if (task && task.id === taskId) {
        setTask(updatedTask);
      }
      
      // 发送实时更新
      if (enableRealtime && isSocketConnected) {
        sendTaskUpdate({
          taskId,
          projectId: updatedTask.projectId,
          update: updateData,
          updatedBy: {
            id: user?.id,
            name: user?.name
          },
          timestamp: Date.now()
        });
      }
      
      if (showNotifications) {
        notifications.success('更新成功', '任务已更新');
      }
      
      return updatedTask;
    } catch (error) {
      handleApiError(error);
      throw error;
    }
  }, [updateTaskApi, tasks, setTasks, task, setTask, enableRealtime, isSocketConnected, sendTaskUpdate, user, showNotifications]);
  
  // 删除任务
  const deleteTask = useCallback(async (taskToDelete: Task) => {
    try {
      // 调用API删除任务
      if (taskId) {
        // 删除单个任务
        await deleteSingleTaskApi();
        
        // 清空本地状态
        setTask(undefined);
      } else {
        // 删除任务列表中的任务
        await deleteTaskApi(`/${taskToDelete.id}`);
        
        // 更新本地状态
        setTasks((prevTasks) => {
          if (!prevTasks) return prevTasks;
          
          return prevTasks.filter((t) => t.id !== taskToDelete.id);
        });
      }
      
      if (showNotifications) {
        notifications.success('删除成功', '任务已删除');
      }
      
      return true;
    } catch (error) {
      handleApiError(error);
      return false;
    }
  }, [taskId, deleteSingleTaskApi, deleteTaskApi, setTask, setTasks, showNotifications]);
  
  // 切换任务状态
  const toggleTaskStatus = useCallback(async (taskToToggle: Task, newStatus: string) => {
    return updateTask(taskToToggle, { status: newStatus });
  }, [updateTask]);
  
  // 分配任务
  const assignTask = useCallback(async (taskToAssign: Task, assigneeId: string) => {
    return updateTask(taskToAssign.id, { assigneeId });
  }, [updateTask]);
  
  // 设置任务优先级
  const setTaskPriority = useCallback(async (taskToUpdate: Task, priority: string) => {
    return updateTask(taskToUpdate.id, { priority });
  }, [updateTask]);
  
  // 设置任务截止日期
  const setTaskDueDate = useCallback(async (taskToUpdate: Task, dueDate: string) => {
    return updateTask(taskToUpdate.id, { dueDate });
  }, [updateTask]);
  
  return {
    // 数据
    tasks,
    task,
    
    // 加载状态
    isLoading: taskId ? isTaskLoading : isTasksLoading,
    error: taskId ? taskError : tasksError,
    
    // 操作
    createTask,
    updateTask,
    deleteTask,
    toggleTaskStatus,
    assignTask,
    setTaskPriority,
    setTaskDueDate,
    
    // 刷新
    refetch: taskId ? refetchTask : refetchTasks
  };
} 